<template>
  <div ref="appContainer" class="app-container home-bg-padding">
    <CustomSearch
      ref="searchForm"
      show-all.sync="false"
      :show-switch-icon="false"
      @search="searchFn"
      @reset="resetFn"
    >
      <template #btns>
        <sec-button
          v-if="permissions(AddMenu)"
          type="primary"
          icon="sec-icon-bianji"
          @click="addDepartment"
          >添加</sec-button
        >
        <sec-tooltip
          class="item"
          effect="dark"
          content="刷新"
          placement="top-start"
        >
          <sec-button
            icon="sec-icon-shuaxin"
            circle
            @click="getList()"
          ></sec-button>
        </sec-tooltip>
      </template>
    </CustomSearch>
    <div class="query-table">
      <sec-table
        v-loading="loading"
        :data="department[0].children"
        size="mini"
        stripe
        row-key="id"
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        style="width: 100%; height: 100%; overflow-y: scroll"
      >
        <sec-table-column fixed prop="name" label="部门名称"></sec-table-column>
        <sec-table-column
          prop="sortOrder"
          label="排序"
          width="70"
        ></sec-table-column>
        <sec-table-column prop="path" label="组件路径"></sec-table-column>
        <sec-table-column
          prop="resourceUrl"
          label="资源路径"
        ></sec-table-column>
        <sec-table-column label="类型" width="70">
          <template slot-scope="scope">
            <sec-tag v-if="scope.row.type === '0'">菜单</sec-tag>
            <sec-tag v-if="scope.row.type === '1'" type="success">按钮</sec-tag>
          </template>
        </sec-table-column>
        <sec-table-column
          prop="permission"
          label="权限标示"
          width="130"
        ></sec-table-column>
        <sec-table-column fixed="right" label="操作">
          <template slot-scope="scope">
            <sec-button
              v-if="permissions(AddMenu)"
              type="text"
              size="small"
              icon="el-icon-plus"
              @click="localAddDepartment(scope.row)"
              >新增</sec-button
            >
            <sec-button
              v-if="permissions(EditMenu)"
              type="text"
              size="small"
              icon="sec-icon-bianji"
              @click="localAddDepartment(scope.row, 'edit')"
              >修改</sec-button
            >
            <sec-button
              v-if="permissions(DeleteMenu)"
              type="text"
              size="small"
              icon="el-icon-delete"
              @click="deleteOpen(scope.row)"
              >删除</sec-button
            >
          </template>
        </sec-table-column>
      </sec-table>
    </div>
    <!-- 编辑弹框 -->
    <sec-dialog
      v-if="visible"
      :title="dialogTitle"
      :visible.sync="visible"
      :close-on-click-modal="false"
    >
      <sec-form ref="formEle" :model="form" :rules="rules" labsec-width="80px">
        <sec-row>
          <sec-col :span="12">
            <sec-form-item label="菜单类型" prop="type">
              <sec-radio-group v-model="form.type">
                <sec-radio-button label="0">菜单</sec-radio-button>
                <sec-radio-button label="1">按钮</sec-radio-button>
              </sec-radio-group>
            </sec-form-item>
          </sec-col>
          <sec-col :span="12">
            <sec-form-item label="上级菜单">
              <sec-cascader
                v-model="parentNode"
                size="medium"
                clearable
                :options="department"
                :props="{ ...defaultProps, checkStrictly: true }"
                :show-all-levels="false"
                @change="selectChange"
              ></sec-cascader>
            </sec-form-item>
          </sec-col>
        </sec-row>
        <sec-form-item label="名称" prop="name">
          <sec-input
            v-model="form.name"
            size="medium"
            placeholder="请输入菜单名称"
          />
        </sec-form-item>
        <sec-form-item v-if="form.type !== '1'" label="路由地址" prop="path">
          <sec-input
            v-model="form.path"
            size="medium"
            placeholder="请输入路由地址"
          />
        </sec-form-item>
        <sec-form-item
          v-if="form.type === '1'"
          label="资源路径"
          prop="resourceUrl"
        >
          <sec-input
            v-model="form.resourceUrl"
            size="medium"
            placeholder="请输入资源路径"
          />
        </sec-form-item>
        <sec-form-item
          v-if="form.type === '1'"
          label="权限标识"
          prop="permission"
        >
          <sec-input
            v-model="form.permission"
            placeholder="请权限标识"
            size="medium"
            maxlength="50"
          />
        </sec-form-item>
        <sec-row>
          <sec-col :span="12">
            <sec-form-item label="排序" prop="sortOrder">
              <sec-input-number
                v-model="form.sortOrder"
                size="medium"
                controls-position="right"
                :min="0"
              />
            </sec-form-item>
          </sec-col>
          <!-- <sec-col :span="12">
            <sec-form-item
              v-if="form.type !== '1'"
              label="路由缓冲"
              prop="keepAlive"
            >
              <sec-radio-group v-model="form.keepAlive">
                <sec-radio-button label="0">否</sec-radio-button>
                <sec-radio-button label="1">是</sec-radio-button>
              </sec-radio-group>
            </sec-form-item>
          </sec-col> -->
        </sec-row>
      </sec-form>
      <div slot="footer" class="dialog-footer">
        <sec-button type="primary" @click="confirm">确 定</sec-button>
        <sec-button @click="visible = false">取 消</sec-button>
      </div>
    </sec-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { DeleteMenu, AddMenu, EditMenu } from '@/const/permissions'
import http from '@/utils/http'
import iconList from '@/const/iconList'
import pagination from '@/utils/mixins/pagination'
import { CustomSearch } from '@/components'
export default {
  name: 'AccessDepartment',
  components: {
    CustomSearch
  },
  mixins: [pagination],
  data: function () {
    return {
      DeleteMenu,
      AddMenu,
      EditMenu,
      fn: 'addNewMenu',
      dialogTitle: '新增',
      department: [{ children: [] }],
      departmentVisible: false,
      formLabelWidth: '120px',
      loading: false,
      selectDepartId: '',
      order: 20,
      defaultProps: {
        children: 'children',
        label: 'name',
        value: 'id'
      },
      parentNode: [],
      tempNode: {},
      visible: false,
      form: {
        name: undefined,
        path: undefined,
        resourceUrl: undefined,
        icon: undefined,
        permission: undefined,
        type: '0',
        // keepAlive: '0',
        sortOrder: 999
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: '菜单名称不能为空', trigger: 'change' }
        ],
        sortOrder: [
          { required: true, message: '菜单顺序不能为空', trigger: 'blur' }
        ],
        path: [
          { required: true, message: '路由地址不能为空', trigger: 'change' }
        ],
        resourceUrl: [
          { required: true, message: '资源路径不能为空', trigger: 'change' }
        ],
        // keepAlive: [
        //   { required: true, message: '路由缓冲不能为空', trigger: 'blur' }
        // ],
        permission: [
          { required: true, message: '权限标识不能为空', trigger: 'change' }
        ]
      },
      iconList: iconList
    }
  },
  computed: {
    ...mapGetters(['permissions'])
  },
  watch: {
    currentPage: function (val) {
      this.getList()
    },
    pageSize: function (val) {
      this.getList()
    }
  },
  created: function () {
    this.getList()
  },
  mounted: function () {},
  methods: {
    getList: function () {
      this.loading = true
      http.getAllMenuList({ lazy: false }).then((res) => {
        // todo ****** 方便后面的数据处理，默认加一级根节点 *****
        const treeNode = [
          {
            children: res.data,
            createTime: '2018-01-22 19:00:23',
            id: '-1',
            isLock: false,
            name: '根菜单',
            // disabled: true,
            parentId: '-11',
            weight: 1
          }
        ]

        /**
         * @description 建立节点引用关系方便后面的引用查找
         */
        const establishRef = (arr, parent) => {
          for (let i = 0; i < arr.length; i++) {
            const node = arr[i]
            parent && (node['parent'] = parent)
            if (Array.isArray(node.children)) {
              establishRef(node.children, node)
            }
          }
        }
        establishRef(treeNode)
        this.department = treeNode

        this.pagination.totalCount = res.data.length

        this.loading = false
      })
    },
    selectChange: function (aSelect) {
      this.parentNode = aSelect
    },
    localAddDepartment: function (node, command) {
      this.tempNode = node
      // 临时变量
      // this.willUpdateNode = node
      const { id } = node
      this.visible = true
      let found = false
      /**
       * @description 递归查找
       * *** 当前递归是深度优先遍历的策略.
       * *** 嵌套for循环遍历的跳出的确是一个小的问题，可以借助try catch之外就只能通过flag方式实现了
       */
      const recursionFindById = (arr, id) => {
        for (let i = 0; i < arr.length; i++) {
          const node = arr[i]
          if (node.id === id) {
            found = node
            break
          }
          if (Array.isArray(node.children) && !found) {
            recursionFindById(node.children, id)
          }
        }
      }

      recursionFindById(this.department, id)

      const idLink = [found.id]
      // 溯源id链
      const findParentId = (node) => {
        const parent = node.parent

        if (!parent) return

        idLink.unshift(parent.id)

        if (parent.id === id) {
          return
        } else {
          findParentId(parent)
        }
      }

      findParentId(found)

      if (command === 'edit') {
        this.dialogTitle = '修改'
        this.fn = 'updateCurrenMenu'
        this.form = {
          name: node.name,
          path: node.path,
          resourceUrl: node.resourceUrl,
          icon: node.icon,
          permission: node.permission,
          type: node.type,
          // keepAlive: node.keepAlive,
          sortOrder: node.sortOrder
        }

        idLink.pop()
      } else {
        this.dialogTitle = '新增'
        this.fn = 'addNewMenu'
        this.form = {
          name: '',
          path: '',
          icon: '',
          permission: '',
          resourceUrl: '',
          type: '0',
          // keepAlive: '0',
          sortOrder: 999
        }
      }

      this.parentNode = idLink
      this.order = 999
    },
    addDepartment: function (user) {
      this.visible = true
      this.dialogTitle = '新增'
      this.fn = 'addNewMenu'
      this.form = {
        name: '',
        path: '',
        icon: '',
        permission: '',
        type: '0',
        // keepAlive: '0',
        sortOrder: 999
      }
    },
    deleteUser: function (user) {
      this.departmentVisible = true
      this.user = user
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    currentChange(node, data) {
      console.log(node)
    },
    confirm: function () {
      this.$refs.formEle.validate((valid) => {
        if (valid) {
          this.departmentVisible = false
          console.log(
            ` [ confirm ] ----`,
            this.parentNode,
            this.form.departmentName,
            this.order,
            this.form
          )

          const param = {
            createBy: ' ',
            createTime: '',
            updateBy: ' ',
            updateTime: '',
            // name: '测试1',
            permission: null,
            parentId: this.parentNode[this.parentNode.length - 1],
            // icon: 'icon-miyue', //
            // path: '/test/11', //
            resourceUrl: null,
            // sortOrder: 999, //
            type: '0',
            // keepAlive: '0', //
            delFlag: '0',
            ...this.form
          }
          if (this.fn === 'updateCurrenMenu') {
            param.menuId = this.tempNode.id
          }
          http[this.fn](param).then((res) => {
            this.$message({
              type: 'success',
              message: `${this.dialogTitle}成功!`
            })
            this.getList()
            this.visible = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    deleteOpen(row) {
      console.log(row)
      this.$confirm(`是否确认删除名称为"${row.name}"的数据项? `, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        type: 'warning'
      })
        .then(() => {
          http.deletsCurrenMenu({ menuId: row.id }).then((res) => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getList()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>
<style scoped lang="scss">
.item {
  width: 30px;
}
</style>

<style scoped lang="scss">
.line {
  padding: 10px 0;
  &.btn {
    padding-top: 0;
  }
  &.page {
    text-align: right;
  }
}
.query-table {
  padding: 8px;
  background: #fff;
  flex: 1;
  height: 1%;
  .operate {
    font-size: 12px;
  }
  .idot {
    width: 8px;
    height: 8px;
    background: #19be6b;
    border-radius: 50%;
    display: inline-block;
    margin-right: 5px;
  }
  .sec-icon-bangzhu1 {
    margin-left: 3px;
    color: rgb(45, 140, 240);
  }
  .pagination {
    text-align: right;
    padding-top: 8px;
    .el-pagination {
      padding-right: 0;
    }
    .el-pagination__sizes {
      margin: 0;
    }
    .el-pagination .el-pagination__sizes .el-select .el-input {
      margin-right: 0;
    }
  }
  .el-table {
    .el-table-column--selection {
      .cell {
        padding-left: 14px;
      }
    }
    .el-table__body {
      width: 100%;
      // 使表格兼容safari，不错位
      table-layout: fixed !important;
    }
  }
}
.item {
  width: 30px;
}
</style>
